<?php
namespace PsiFramework\Applications\AlloMediaAdmin\Classes\Actions\CMS;

import("Classes.Factory.DAOFactory");
import("Classes.Factory.ObjectFactory");
import("Classes.Util.Object.Json");
import("Plugins.Form.Classes.Util.Json.JsonForm");
import("Plugins.CMS.Classes.Actions.SaveAction");
import("Classes.Util.Manager.ObjectManager");

use \PsiFramework\Classes\DAO\DAOInterface\IDAO;
use \PsiFramework\Classes\Model\Object;
use \PsiFramework\Classes\Factory\DAOFactory;
use \PsiFramework\Classes\Factory\ObjectFactory;
use \PsiFramework\Classes\Util\Object\Date;
use \PsiFramework\Classes\Util\Object\EMail;
use \PsiFramework\Classes\Util\Object\File;
use \PsiFramework\Classes\Util\Object\Image;
use \PsiFramework\Classes\Util\Object\ImageCollection;
use \PsiFramework\Classes\Util\Object\Json;
use \PsiFramework\Classes\Util\Object\ReferenceObject;
use \PsiFramework\Classes\Util\Parameters\JsonParameters;
use \PsiFramework\Plugins\Form\Classes\Util\Json\JsonForm;
use \PsiFramework\Plugins\CMS\Classes\Actions\SaveAction;
use \PsiFramework\Classes\Util\Manager\ApplicationManager;
use \PsiFramework\Classes\Util\Manager\ObjectManager;
use \PsiFramework\Classes\Util\Manager\ParametersManager;

/**
 * Bibliotheque
 * Gestion de ma bibliothèque
 *
 * @author Rémi San
 * @version beta
 */

/**
 * Classe d'action de sauvegarde
 *
 * @package Actions
 */
class AlloMediaSaveAction extends SaveAction
{

    public function getAlloMediaEntry(IDAO $dao, Object $obj)
    {
        $obj->setId($this->_request->getParameter('id'));

        $obj->setModificationDate(Date::now());

        $userId = $this->_request->getParameter('user_id');
        $user = null ;
        if (!isNullOrEmptyString($userId)) {
            $userDAO = DAOFactory::getDAO('User');
            $user = $userDAO->retrieveByPk($userId);
        }
        $obj->setUser($user);

        $categoryId = $this->_request->getParameter('category_id');
        $category = null ;
        if (!isNullOrEmptyString($categoryId)) {
            $categoryDAO = DAOFactory::getDAO('SiteCategory');
            $category = $categoryDAO->retrieveByPk($categoryId);
        }
        $obj->setCategory($category);

        $obj->setName($this->_request->getParameter('name'));
        $obj->setAddress($this->_request->getParameter('address'));
        $obj->setCity($this->_request->getParameter('city'));
        $obj->setZip($this->_request->getParameter('zip'));
        $obj->setTel($this->_request->getParameter('tel'));

        $dao->save($obj, false);

        $sites = $this->getParts(
            array(
                'setter'=>'setEntry',
                'value'=>$obj
            ),
            array(
                'name'=>'SiteMembership'
            ), 
            array(
                'name'=>'AlloMediaSite', 
                'setter'=>'setSite'
            ), 
            array(
                array(
                    'name'=>'id_for_site',
                    'setter'=>'setSiteUserId'
                )
            ), 
            'site', 
            false
        );
        $obj->setSites($sites);

        return $obj ;
    }

    public function getUser(IDAO $dao, Object $obj)
    {
        $obj->setId($this->_request->getParameter('id'));
        $obj->setLogin($this->_request->getParameter('login'));

        if (is_null($obj->getId())) {
            $obj->setCreationDate(Date::now());
        }

        $pwd = $obj->getPassword();
        $decryptedPwd = null ;
        if (is_null($pwd)) {
            $decryptedPwd = uniqid();
            $pwd = md5($decryptedPwd);
            $obj->setPassword($pwd);
        }

        $email = $this->_request->getParameter('email');
        if (is_null($email)) {
            throw new \Exception("e-mail must be not null !");
        }
        $obj->setEmail($email);

        $obj->setActivated(true);
        $obj->setBlocked(false);

        $dao->save($obj, false);

        $securityRoleDao = DAOFactory::getDAO("SecurityRole");
        $userRoleDao = DAOFactory::getDAO("SecurityUserRole");

        $roles = $this->_request->getParameter('role');
        if (!isNullOrEmptyString($roles)) {
            $retrievedRoles = $obj->getRoles();
            if (!is_null($retrievedRoles)) {
                foreach ($retrievedRoles as $retrievedRole) {
                    $role = $retrievedRole->getRole();
                    if (!is_null($role)) {
                        if (!in_array($role->getName(), $roles)) {
                            if ($role->getName() == 'allomedia_user'
                                || $role->getName() == 'allomedia_admin'
                            ) {
                                $userRoleDao->delete($retrievedRole);
                            }
                        }
                    }
                }
            }

            foreach ($roles as $role) {
                $securityRole = $securityRoleDao->getRoleByName($role);
                $userRoleModel
                    = ObjectFactory::getNewObject("SecurityUserRole");
                $userRoleModel->setUser($obj);
                $userRoleModel->setRole($securityRole);

                $userRole = $userRoleDao->retrieveByPk($userRoleModel->getId());

                if (is_null($userRole)) {
                    $userRoleDao->save($userRoleModel);
                }
            }
        }

        if (!is_null($decryptedPwd)) {

            $paramManager = ParametersManager::getInstance();
            $applicationsParameters
                = $paramManager->getApplicationsParameters();

            $contact = $applicationsParameters->getContact();
            $subject = "Inscription" ;
            $message = $decryptedPwd ;

            $application = ApplicationManager::getInstance()->getApplication();
            $appConfigDao = DAOFactory::getDAO('ApplicationConfiguration');
            $appConfig = $appConfigDao->retrieveByName($application->getName());

            if (!is_null($appConfig)) {
                $contact = $appConfig->getParameters()->get('email');
                $page = $appConfig->getParameters()
                    ->get('inscription_message')->getObject();
                if (!is_null($page)) {
                    $subject = $page->getTitle();
                    $message = str_replace(
                        '<password>',
                        $decryptedPwd,
                        $page->getContent()
                    );
                }
            }

            $email = new EMail($contact, $obj->getEmail(), $subject, $message);
            //send email to the user
            $email->send();
        }

        return $obj ;
    }

    public function getInformationProfile(IDAO $dao, Object $obj)
    {
        $obj->setId($this->_request->getParameter('id'));
        $obj->setName($this->_request->getParameter('name'));
        $obj->setText($this->_request->getParameter('text'));

        $now = Date::now();

        if (isNullOrEmptyString($obj->getId())) {
            $obj->setCreationDate($now);
        }
        $obj->setModificationDate($now);

        $dao->save($obj, false);

        $parts = $this->getParts(
            array(
                'setter'=>'setProfile',
                'value'=>$obj
            ),
            array(
                'name'=>'InformationPart'
            ),
            array(
                'name'=>'Form',
                'setter'=>'setTheme'
            ),
            array(
                array(
                    'name'=>'part_order',
                    'setter'=>'setOrder'
                ),
                array(
                    'name'=>'points',
                    'setter'=>'setPoints'
                ),
                array(
                    'name'=>'price',
                    'setter'=>'setPrice'
                )
            ),
            '',
            true
        );
        $obj->setParts($parts);

        return $obj ;
    }

    public function getAlloMediaSite(IDAO $dao, Object $obj)
    {
        $obj->setId($this->_request->getParameter('id'));
        $obj->setName($this->_request->getParameter('name'));
        $obj->setUri($this->_request->getParameter('uri'));

        $profileId = $this->_request->getParameter('profile_id');
        if (!isNullOrEmptyString($profileId)) {
            $profileDao = DAOFactory::getDAO('InformationProfile');
            $profile = $profileDao->retrieveByPk($profileId);
            if (!is_null($profile)) {
                $obj->setProfile($profile);
            }
        }

        $styleId = $this->_request->getParameter('style_id');
        if (!isNullOrEmptyString($styleId)) {
            $styleDao = DAOFactory::getDAO('Style');
            $style = $styleDao->retrieveByPk($styleId);
            if (!is_null($style)) {
                $obj->setStyle($style);
            }
        }

        $dao->save($obj, false);

        $parts = $this->getParts(
            array(
                'setter'=>'setSite',
                'value'=>$obj
            ),
            array(
                'name'=>'CategoryLink'
            ),
            array(
                'name'=>'SiteCategory',
                'setter'=>'setCategory'
            ),
            array(
                array(
                    'name'=>'id_for_site',
                    'setter'=>'setIdForSite'
                )
            ),
            '',
            false
        );
        $obj->setCategories($parts);

        return $obj ;
    }

    public function getSiteCategory(IDAO $dao, Object $obj)
    {
        $obj->setId($this->_request->getParameter('id'));
        $obj->setName($this->_request->getParameter('name'));

        $profileId = $this->_request->getParameter('profile_id');
        if (!isNullOrEmptyString($profileId)) {
            $profileDao = DAOFactory::getDAO('InformationProfile');
            $profile = $profileDao->retrieveByPk($profileId);
            if (!is_null($profile)) {
                $obj->setProfile($profile);
            }
        }

        $styleId = $this->_request->getParameter('style_id');
        if (!isNullOrEmptyString($styleId)) {
            $styleDao = DAOFactory::getDAO('Style');
            $style = $styleDao->retrieveByPk($styleId);
            if (!is_null($style)) {
                $obj->setStyle($style);
            }
        }

        $dao->save($obj, false);

        $parts = $this->getParts(
            array(
                'setter'=>'setCategory',
                'value'=>$obj
            ),
            array(
                'name'=>'CategoryLink'
            ),
            array(
                'name'=>'AlloMediaSite',
                'setter'=>'setSite'
            ),
            array(
                array(
                    'name'=>'id_for_site',
                    'setter'=>'setIdForSite'
                )
            ),
            '',
            false
        );
        $obj->setSites($parts);

        return $obj ;
    }
    
    public function getForm(IDAO $dao, Object $obj)
    {
        $obj->setId($this->_request->getParameter('id'));
        $obj->setName($this->_request->getParameter('name'));
        $obj->setTitle($this->_request->getParameter('title'));
        $obj->setPresentationTitle($this->_request->getParameter('presentation_title'));
        $obj->setComplementTitle($this->_request->getParameter('complement_title'));
        $obj->setPresentation(ckEditorFilter($this->_request->getParameter('presentation')));
        $obj->setComplement(ckEditorFilter($this->_request->getParameter('complement')));
        $obj->setImage($this->getImage('image', './Images/Upload', 223, 208, $obj->getImage()));
        $obj->setComplementImage($this->getImage('complement_image', './Images/Upload', 223, 152, $obj->getComplementImage()));
        
        $multipleImages = null;
        $multipleImagesName = 'slider_image';
        $count = $this->_request->getParameter($multipleImagesName.'_count');
        if ($count>0) {
            $multipleImages = new ImageCollection();
            $previousMultipleImages = $obj->getSliderImages();
            for ($i=0;$i<$count;$i++) {
                $previousImage = null;
                if (!is_null($previousMultipleImages)) {
                    $previousImage = $previousMultipleImages->getImage($i);
                }
                $im = $this->getImage($multipleImagesName.'_'.$i, './Images/Upload', 445, 91, $previousImage);
                if (!is_null($im)) {
                    $multipleImages->addImage($im);
                }
            }
        }
        $obj->setSliderImages($multipleImages);
        
        if ($this->countParts('')>0) {
            if (isNullOrEmptyString($obj->getId())) {
                $obj->setCreationDate(Date::now());
                $dao->save($obj, false);
            }
            $obj->setModificationDate(Date::now());

            $parts = $this->getParts(
                array(
                    'setter'=>'setForm',
                    'value'=>$obj
                ),
                array(
                    'name'=>'FormFieldLink'
                ),
                array(
                    'name'=>'FormField',
                    'setter'=>'setField'
                ),
                array(
                    array(
                        'name'=>'part_order',
                        'setter'=>'setOrder'
                    ),
                    array(
                		'name'=>'group',
                		'setter'=>'setGroupName'
                    ),
                    array(
                		'name'=>'group_title',
                		'setter'=>'setGroupTitle'
                    )
                ),
                '',
                false
            );
            $obj->setFields($parts);
        } else {
            $obj = null ;
            throw new \Exception('The form must have fields !');
        }

        return $obj ;
    }

    public function getStyle(IDAO $dao, Object $obj)
    {
        $obj->setId($this->_request->getParameter('id'));
        $obj->setName($this->_request->getParameter('name'));
        $obj->setCss($this->_request->getParameter('css'));

        return $obj ;
    }

    public function getPage(IDAO $dao, Object $obj)
    {
        $obj->setId($this->_request->getParameter('id'));
        $obj->setName($this->_request->getParameter('name'));
        $obj->setLanguage($this->_request->getParameter('lang'));
        $obj->setTitle($this->_request->getParameter('title'));
        $obj->setContent($this->_request->getParameter('content'));

        return $obj ;
    }

    public function getApplicationConfiguration(IDAO $dao, Object $obj)
    {
        $obj->setId($this->_request->getParameter('id'));
        $obj->setName($this->_request->getParameter('name'));

        $parameters = new JsonParameters();
        $parameters->set('email', $this->_request->getParameter('email'));

        $pageDao = DAOFactory::getDAO('Page');
        $inscriptionId = $this->_request->getParameter('inscription_id');
        $newPasswordId = $this->_request->getParameter('new_password_id');

        $inscription = null ;
        if (!isNullOrEmptyString($inscriptionId)) {
            $inscription = $pageDao->retrieveByPk($inscriptionId);
        }
        
        $newPassword = null ;
        if (!isNullOrEmptyString($newPasswordId)) {
            $newPassword = $pageDao->retrieveByPk($newPasswordId);
        }

        if (!is_null($inscription)) {
            $parameters->set(
                'inscription_message',
                new ReferenceObject('Page', $inscription->getId())
            );
        }
        if (!is_null($newPassword)) {
            $parameters->set(
                'new_password_message',
                new ReferenceObject('Page', $newPassword->getId())
            );
        }

        $obj->setParameters($parameters);

        return $obj ;
    }

    public function getFieldType(IDAO $dao, Object $obj)
    {
        $obj->setId($this->_request->getParameter('id'));

        $name = $this->_request->getParameter('name');
        $obj->setName($name);
        
        $jsonFormDao
            = ObjectManager::getInstance()->
                           getPrimitiveObjectDaoInstance('JsonForm');
        $jsonForm = $jsonFormDao->parse(
            $this->_request->getParameter('fields')
        );
        $obj->setStructure($jsonForm);
        
        $responseParameters
            = $dao->getResponseParametersFromJsonForm($name, $jsonForm);
        $obj->setResponseParameters($responseParameters);

        return $obj ;
    }

    public function getFormField(IDAO $dao, Object $obj)
    {
        $fieldTypeId = $this->_request->getParameter('field_type');
        $fieldType = null ;
        if (!isNullOrEmptyString($fieldTypeId)) {
            $fieldTypeDAO = DAOFactory::getDAO('FieldType');
            $fieldType = $fieldTypeDAO->retrieveByPk($fieldTypeId);
        }
        if (!is_null($fieldType)) {
            $obj->setName($this->_request->getParameter('name'));
            $obj->setType($fieldType);

            $jsonForm = $fieldType->getStructure();

            $jsonValues = new Json();
            foreach ($jsonForm->getElements() as $field) {
                foreach ($field->getElements() as $element) {
                    $label = $element->getLabel();
                    if (startsWith($label, '<') && endsWith($label, '>')) {
                        $label = substr($label, 1, strlen($label)-2);
                        $value = $this->_request
                            ->getParameter('field_value_'.$label);
                        $jsonValues->getObject()->{$label} = $value ;
                    }
                }
            }
            $obj->setValues($jsonValues);
        }

        return $obj ;
    }
    
    public function getItemCategory(IDAO $dao, Object $obj)
    {
    	$obj->setId($this->_request->getParameter('id'));
        $obj->setName($this->_request->getParameter('name'));
        $obj->setDescription($this->_request->getParameter('description'));
        
        $parentId = $this->_request->getParameter('parent_category_id');
        $parent = $dao->retrieveByPk($parentId);
        $obj->setParent($parent);
    
    	return $obj ;
    }
    
    public function getResponseId(IDAO $dao, Object $obj)
    {
    	$obj->setPaid(!isNullOrEmptyString($this->_request->getParameter('paid')));
    	$expirationDateString = $this->_request->getParameter('expirationDate');
    	$expirationDate = null;
    	if (!isNullOrEmptyString($expirationDateString)) {
    	    $expirationDate = Date::getDateFromFrenchString($expirationDateString);
    	}
    	$obj->setExpirationDate($expirationDate);
    
    	return $obj ;
    }
    
    public function getText(IDAO $dao, Object $obj)
    {
    	$obj->setKey($this->_request->getParameter('key'));
    	$obj->setFr($this->_request->getParameter('fr'));
    	$obj->setEn($this->_request->getParameter('en'));
    	
    	return $obj ;
    }
    
    public function getDiscount(IDAO $dao, Object $obj)
    {
    	$obj->setId($this->_request->getParameter('id'));
    	$obj->setCode($this->_request->getParameter('code'));
    
    	$categoryDao = DAOFactory::getDAO('ItemCategory');
    	$category = $categoryDao->retrieveByPk($this->_request->getParameter('category_id'));
    	$obj->setCategory($category);
    
    	$minQuantity = $this->_request->getParameter('min_quantity');
    	if (isNullOrEmptyString($minQuantity)) {
    	    $minQuantity = null;
    	}
    	$obj->setMinQuantity($minQuantity);
    	
    	$maxQuantity = $this->_request->getParameter('max_quantity');
    	if (isNullOrEmptyString($maxQuantity)) {
    		$maxQuantity = null;
    	}
    	$obj->setMaxQuantity($maxQuantity);
    	
    	$obj->setValue($this->_request->getParameter('value'));
    	$obj->setPercentage($this->_request->getParameter('percentage')=='1');
    	
    	return $obj ;
    }

}
